// src/utils.c

#include <stdio.h>
#include <conio.h> // 用于 getch()，如果在 Unix-like 系统下，请替换为适当的库
#include <windows.h>
#include "utils.h"
#include "snake.h"
#include "food.h"

void initUtils() {
    system("cls"); // 如果在Windows环境，请替换为 system("cls");
}

void gotoxy(int x, int y) {
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void renderInitialGame(Snake* snake, Food* food) {
    system("cls"); // 清屏，如果是Linux/macOS，请使用 "clear"
    for (int y = 0; y < GAME_HEIGHT; y++) {
        for (int x = 0; x < GAME_WIDTH; x++) {
            if (x == 0 || y == 0 || x == GAME_WIDTH - 1 || y == GAME_HEIGHT - 1) {
                putchar('*');
            } else if (x == food->position.x && y == food->position.y) {
                putchar(FOOD_CHAR);
            } else {
                putchar(' ');
            }
        }
        putchar('\n');
    }
}

void renderGame(Snake* snake, Food* food, int score) {
    // 清除蛇的尾部
    int tailX = snake->body[snake->length - 1].x;
    int tailY = snake->body[snake->length - 1].y;

    if (tailX != 0 && tailY != 0 && tailX != GAME_WIDTH - 1 && tailY != GAME_HEIGHT - 1) {
        gotoxy(tailX, tailY);
        printf(" ");
    }

    // 将蛇头的新位置设置为蛇头字符
    gotoxy(snake->body[0].x, snake->body[0].y);
    printf("%c", SNAKE_HEAD);

    // 如果蛇吃到食物，我们不清除该位置，否则，我们会清除蛇的尾部位置
    if (!isFoodEaten(food, snake)) {
        gotoxy(food->position.x, food->position.y);
        printf("%c", FOOD_CHAR);
    }

    // 更新得分
    gotoxy(0, GAME_HEIGHT + 1);
    printf("得分：%d   ", score);  // 为了确保覆盖以前的分数，我们在其后加了一些空格
}


Direction getInput() {
    char ch = getch(); // 获取键盘输入，不需要回车
    switch (ch) {
        case 'w':
            return UP;
        case 's':
            return DOWN;
        case 'a':
            return LEFT;
        case 'd':
            return RIGHT;
        default:
            return -1; // 无效输入
    }
}
